package com.mingqijia.gassafety.job.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gap.cache.redis.RedisCache;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mingqijia.gassafety.authority.api.resp.config.DictionaryItemRespDTO;
import com.mingqijia.gassafety.authority.dal.helper.ConfigureHolder;
import com.mingqijia.gassafety.db.entity.*;
import com.mingqijia.gassafety.db.entity.redis.DetectorMeasure;
import com.mingqijia.gassafety.db.entity.redis.DtuMeasure;
import com.mingqijia.gassafety.db.entity.redis.LatestDetector;
import com.mingqijia.gassafety.db.entity.redis.LatestLog;
import com.mingqijia.gassafety.db.entity.vo.DeviceStateVO;
import com.mingqijia.gassafety.db.entity.vo.LatestLogListVO;
import com.mingqijia.gassafety.db.entity.vo.ValveInfoVO;
import com.mingqijia.gassafety.db.mapper.DtuAepMapper;
import com.mingqijia.gassafety.db.mapper.DtuMapper;
import com.mingqijia.gassafety.db.mapper.ValveInfoMapper;
import com.mingqijia.gassafety.job.feign.ConsoleSkFeignClient;
import com.mingqijia.gassafety.job.request.ConsoleSkSupplierListRequest;
import com.mingqijia.gassafety.job.request.ConsumerListRequest;
import com.mingqijia.gassafety.job.request.LatestLogListRequest;
import com.mingqijia.gassafety.job.response.*;
import com.mingqijia.gassafety.job.service.*;
import com.mingqijia.gassafety.job.service.cmp.EquipmentCmpService;
import com.mingqijia.gassafety.shared.constant.*;
import com.mingqijia.gassafety.shared.dto.UserFuncCodePermissionDTO;
import com.mingqijia.gassafety.shared.utils.ApplicationUtils;
import com.mingqijia.gassafety.shared.utils.RedisCacheExt;
import com.mingqijia.gassafety.shared.utils.commonUtils.PageUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.mingqijia.gassafety.shared.constant.Constants.ORG_MAP_SUBSCODE;

/**
 * <p>
 *
 * @author wanghai
 * @since 2022-03-09
 */

@Slf4j
@Service
public class LatestLogServiceImpl implements LatestLogService {
    @Autowired
    DtuMapper dtuMapper;
    @Autowired
    RedisCacheExt redisCacheExt;
    @Autowired
    ConfigureHolder holder;
    @Autowired
    EquipmentService equipmentService;
    @Autowired
    ConsumerService consumerService;
    @Autowired
    RedisCache redisCache;
    @Autowired
    DtuAepMapper dtuAepMapper;
    @Autowired
    DeviceStateService deviceStateService;
    @Autowired
    OrganizationService organizationService;
    @Autowired
    ValveInfoMapper valveInfoMapper;
    @Autowired
    ContactsServiceImpl  contactsService;
    @Autowired
    CompanyService companyService;
    @Autowired
    UserPermissionService userPermissionService;

    @Autowired
    EquipmentCmpService equipmentCmpService;

    @Override
    public PageUtil<LatestLogResponse> list(LatestLogListRequest request) {
        List<LatestLogResponse> resultList = new ArrayList<>();
        LatestLogListVO params = new LatestLogListVO();
        //1.查询条件封装
        BeanUtils.copyProperties(request, params);

        //1.1所属组织
        String spId = ApplicationUtils.getWorkingSpId();
        List<String> spIds = organizationService.getSpIds(spId);
        if (!StringUtils.isEmpty(request.getSpId()) && !spId.equals(request.getSpId())) {
            //如果查询条件不为空，按查询条件来
            spIds.clear();
            spIds.add(request.getSpId());
        }
        params.setSpIds(spIds);

        //组织列表
        List<OrganizationResponse> organizationList = organizationService.getList(ApplicationUtils.getWorkingSpId());

        //params.setSpId(spId);
        List<Integer> equipmentStatus = new ArrayList<>();
        if (request.getEquipmentStatus() != null && EquipmentStatus.lowAlert == request.getEquipmentStatus()) {
            equipmentStatus.add(EquipmentStatus.lowAlert);
            equipmentStatus.add(EquipmentStatus.highAlert);
        } else {
            if (request.getEquipmentStatus() != null) {
                equipmentStatus.add(request.getEquipmentStatus());
            }
        }
        //查询组织架构名称
        List<CompanyListResponse> companyNameList = companyService.queryCompanyNameList(spIds);
        Map<String, String> companyNameMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(companyNameList)) {
            companyNameMap = companyNameList.stream().collect(Collectors.toMap(CompanyListResponse::getSpId, CompanyListResponse::getName));
        }
        //批量查询字典
        List<DictionaryItemRespDTO> orgMapSubsCodeList = holder.getDictionaryByKey(ORG_MAP_SUBSCODE);
        Map<String, String> orgSubsCodeMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(orgMapSubsCodeList)) {
            orgSubsCodeMap = orgMapSubsCodeList.stream().collect(Collectors.toMap(DictionaryItemRespDTO::getDescription, DictionaryItemRespDTO::getCompanyName));
        }
        params.setEquipmentStatus(equipmentStatus);

        //数据权限
        UserFuncCodePermissionDTO userFuncCodePermission = userPermissionService.getUserDepartPermission(spIds);
        params.setFuncCodes(userFuncCodePermission.getFuncCodes());

        PageUtil<DeviceStateVO> deviceStatePage = deviceStateService.getDeviceStateList(params);
        if (!CollectionUtils.isEmpty(deviceStatePage.getList())) {
            //设备类型名称
            List<DictionaryItemRespDTO> equipmentTypeDictList = holder.getDictionaryByKey(
                    EquipmentType.DICT_CODE,request.getSpId());
            //行业类型名称
            List<DictionaryItemRespDTO> industryTypeDictList = holder.getDictionaryByKey(
                    Constants.INDUSTRY_TYPE_CODE,request.getSpId());
            //运营商列表
            List<DictionaryItemRespDTO> operatorList = holder.getDictionaryByKey(Constants.OPERATOR_CODE);
            //设备厂商名称
            ConsoleSkSupplierListResponse response = equipmentCmpService.supplierListRequest();
            log.info("调用厨房查询厂商接口返回：{}", response);
            List<AlarmSupplierListVo> supplierListVos = new ArrayList<>();
            if (response != null && response.getCode() == 0 && response.getData() != null && org.apache.commons.collections.CollectionUtils.isNotEmpty(response.getData())) {
                supplierListVos = response.getData();
            }

            for (DeviceStateVO deviceStateVO : deviceStatePage.getList()) {
                LatestLogResponse res = new LatestLogResponse();
                BeanUtils.copyProperties(deviceStateVO, res);
                if (org.apache.commons.lang3.StringUtils.isNotEmpty(deviceStateVO.getOrgCode()) && orgSubsCodeMap.containsKey(deviceStateVO.getOrgCode())) {
                    res.setCompanyName(orgSubsCodeMap.get(deviceStateVO.getOrgCode()));
                } else {
                    if (companyNameMap.containsKey(deviceStateVO.getSpId())) {
                        res.setCompanyName(companyNameMap.get(deviceStateVO.getSpId()));
                    }
                }

                //设备类型名称
               res.setEquipmentTypeName(getName(equipmentTypeDictList, res.getEquipmentType()));
                //行业类型
                res.setIndustryTypeName(getName(industryTypeDictList, res.getIndustryType()));
                //气体浓度
                if (deviceStateVO.getEquipmentType().equals(EquipmentType.GAS_ALARM_CONTROLLER.getCode())) {
                    res.setXlel("");
                } else {
                    res.setXlel(deviceStateVO.getConcentration() + " %LEL");
                }
                //设备状态  0:离线 1:正常 2:低报 3:高报 4:故障 5:屏蔽
                String status = new String();
                switch (res.getEquipmentStatus()){
                    case 0: status="离线";break;
                    case 1: status="正常";break;
                    case 2: status="低报";break;
                    case 3: status="高报";break;
                    case 4: status="故障";break;
                    case 5: status="屏蔽";break;
                }
                //信号情况
                res.setSignalStr(SignalEnum.getName(res.getSignal()));
                res.setEquipmentStatusName( status );

                //处理状态
                if (res.getWorkOrderCount() != null && res.getWorkOrderCount() > 0) {
                    res.setHandleStatus(AsstConstants.HANDLE_STATUS_1);
                }else {
                    res.setHandleStatus(AsstConstants.HANDLE_STATUS_2);
                }

                //设备设备厂商
                List<AlarmSupplierListVo> listVos = supplierListVos.stream().filter(a -> a.getAlarmSystemCode().equals(
                        res.getEquipmentManufacturer())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(listVos)) {
                    res.setEquipmentManufacturer(listVos.get(0).getMsName());
                }
                //运营商
                res.setOperators(getName(operatorList, res.getOperators()));
                resultList.add(res);
                //所属组织
                if(!CollectionUtils.isEmpty(organizationList)){
                    List<OrganizationResponse> collect = organizationList.stream()
                            .filter(a -> a.getSpId().equals(res.getSpId())).collect(Collectors.toList());
                    if(!CollectionUtils.isEmpty(collect)){
                        res.setSpName(collect.get(0).getSpName());
                    }
                }
                //设备是否携带电磁阀
                res.setHasValve(deviceStateVO.getValveInfoId() == 0 ? "-":"有");
            }
        }
        if (!CollectionUtils.isEmpty(resultList)) {
            List<Integer> consumerIds= resultList.stream().map(LatestLogResponse::getConsumerId).collect(Collectors.toList());
            Map<Integer, List<Contacts>> contacts = contactsService.getContacts(consumerIds, spId);
            if (MapUtils.isNotEmpty(contacts)) {
                resultList.forEach(latestLogResponse -> {
                    latestLogResponse.setContact(dealContacts(contacts.get(latestLogResponse.getConsumerId())
                    ));
                });
            }
        }

        PageUtil pageInfo = new PageUtil<>(request.getPage(), request.getPageSize(), deviceStatePage.getTotal(), resultList);
        return pageInfo;
    }

    private String getName(List<DictionaryItemRespDTO> list, String  value) {
        if( !CollectionUtils.isEmpty(list)){
            List<DictionaryItemRespDTO> respDTOS = list.stream()
                    .filter(dict -> dict.getValue().equals(value)).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(respDTOS)){
                return respDTOS.get(0).getName();
            }
        }
        return null;
    }

    @Override
    public LatestLog get(String imei,String spId) {
        LatestLog log = new LatestLog();
        DeviceStateVO deviceStateVO = deviceStateService.getDeviceStateByImei(imei,spId);
        BeanUtils.copyProperties(deviceStateVO, log);
        log.setIMEI(deviceStateVO.getImei());
        log.setSignalStr(SignalEnum.getName(log.getSignal()));
        if (deviceStateVO.getConcentration() == null) {
            log.setXlel(0+"%LEL");
        } else {
            log.setXlel(deviceStateVO.getConcentration()+"%LEL");
        }
        //离线时，浓度和信号都无
        if (EquipmentStatus.offline == deviceStateVO.getEquipmentStatus()) {
            log.setXlel(null);
            log.setSignal(null);
            log.setSignalStr(null);
        }
        return log;
    }

    @Override
    public List<LatestLogListResponse> getList(List<Integer> consumerIds ,ConsumerListRequest request) {
        List<LatestLogListResponse> resultList = new ArrayList<>();
        //查询所有设备
        QueryWrapper<Dtu> dtuQueryWrapper = new QueryWrapper<>();
        dtuQueryWrapper.lambda().eq( Dtu::getSpId,request.getSpId()  )
                .in( Dtu::getConsumerId,consumerIds )
                .eq( Dtu::getIsDeleted, Constants.IS_DELETED_FALSE );
        List<Dtu> dtuList = dtuMapper.selectList( dtuQueryWrapper );
        //设备厂商名称
        ConsoleSkSupplierListResponse response = equipmentCmpService.supplierListRequest();
        log.info("调用厨房查询厂商接口返回：{}", response);
        List<AlarmSupplierListVo> supplierListVos = new ArrayList<>();
        if (response != null && response.getCode() == 0 && response.getData() != null && org.apache.commons.collections.CollectionUtils.isNotEmpty(response.getData())) {
            supplierListVos = response.getData();
        }
        List<DictionaryItemRespDTO> detectionType = holder.getDictionaryByKey( "Detection_type" );
        List<DictionaryItemRespDTO> operator = holder.getDictionaryByKey( "Operator" );
        List<DictionaryItemRespDTO> equipmentType = holder.getDictionaryByKey( EquipmentType.DICT_CODE);
        List<DictionaryItemRespDTO> valveManufacturers = holder.getDictionaryByKey( Constants.VALVE_MANUFACTURE_CODE);
        //根据设备号,获得开通时间
        List<String> imeiList = dtuList.stream().map(Dtu::getIMEI).collect(Collectors.toList());

        if (CollectionUtil.isNotEmpty(imeiList)){
            QueryWrapper<DtuAep> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().in(DtuAep::getIMEI,imeiList)
                    .eq(DtuAep::getIsDeleted, Constants.IS_DELETED_FALSE)
                    .eq(DtuAep::getSpId, request.getSpId());
            List<DtuAep> dtuAepList = dtuAepMapper.selectList(queryWrapper);
            for (Dtu equipment : dtuList) {
                LatestLogListResponse res = new LatestLogListResponse();
                BeanUtils.copyProperties(equipment,res);
                res.setImei(equipment.getIMEI());
                res.setEquipmentName(equipment.getName());
                res.setEquipmentTypeName( EquipmentType.parse(equipment.getEquipmentType()).getName());
                res.setLocation(equipment.getPositionLon()+","+equipment.getPositionLat());
                //设备厂商字典
                for (AlarmSupplierListVo dto : supplierListVos) {
                    if (dto.getAlarmSystemCode().equals( equipment.getEquipmentManufacturer() )){
                        res.setEquipmentManufacturer( dto.getMsName() );
                    }
                }

                //最新上报信息
                LatestLog latestLog = this.get(equipment.getIMEI(),equipment.getSpId());
                if (latestLog != null) {
                    log.info( "latestLost : {}", latestLog.toString() );
                    BeanUtils.copyProperties(latestLog,res);

                }
                //设备类型
                DictionaryItemRespDTO equipmentTypeDto = equipmentType.stream()
                        .filter( t -> t.getValue().equals( equipment.getEquipmentType() ) )
                        .collect( Collectors.toList() ).get( 0 );
                equipment.setEquipmentType( equipmentTypeDto.getName() );
                //检测类型
                String[] typeList = equipment.getDetectionType().split(";");
                StringBuffer stringBuffer = new StringBuffer("");
                for (String type : typeList) {
                    for (DictionaryItemRespDTO dto : detectionType) {
                        if (dto.getValue().equals(type)){
                            stringBuffer.append( dto.getName()+";");
                        }
                    }
                }
                res.setDetectionType( stringBuffer.toString());
                //运营商
                for (DictionaryItemRespDTO dto : operator) {
                    if (dto.getValue().equals( equipment.getOperators() )) res.setOperators( dto.getName() );
                }
                //开通时间, 点型探测器没有这个时间
                List<DtuAep> aepList = dtuAepList.stream().filter(d -> d.getIMEI().equals(equipment.getIMEI())).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(aepList)){
                    res.setBindingTime(aepList.get(0).getOpenTime());
                }
                //电磁阀信息匹配
                if (equipment.getValveInfoId() != 0){
                    ValveInfoVO valveInfos = valveInfoMapper.getValveInfos(equipment.getIMEI(), equipment.getValveInfoId());
                    BeanUtils.copyProperties(valveInfos, res);
                    List<DictionaryItemRespDTO> dtos = valveManufacturers.stream()
                            .filter(item -> item.getValue().equals(valveInfos.getValveManufacturer())).collect(Collectors.toList());
                    res.setValveManufacturer(CollectionUtils.isEmpty(dtos) ? null: dtos.get(0).getName());
                }
                resultList.add(res);
            }
        }

        return resultList;
    }

    //    @Override
//    public PageUtil<LatestLogResponse> listByStatus(LatestLogListRequest request) {
//        List<LatestLogResponse> resultList = new ArrayList<>();
//        int total = 0;
//        String spId = request.getSpId();
//
//        if (request.getEquipmentTypes() == null || request.getEquipmentTypes().length == 0) {
//            //查询全部
//            request.setEquipmentTypes(new String[]{EquipmentType.INDEPENDENT_GAS_DETECTOR.getCode(),
//                    EquipmentType.POINT_TYPE_GAS_DETECTOR.getCode(),EquipmentType.HOME_GAS_DETECTOR.getCode(),
//                    EquipmentType.GAS_ALARM_CONTROLLER.getCode()});
//        }
//        request.setSpId(spId);
//        PageHelper.startPage(request.getPage(), request.getPageSize());
//        List<Dtu> equipmentList = equipmentService.queryEquipmentList(request);
//
//        if (!equipmentList.isEmpty()) {
//            Map<String,JSONObject> map = redisCache.getCacheMap("department_"+equipmentList.get(0).getPath());
//            for (Dtu equipment : equipmentList) {
//                LatestLogResponse res = new LatestLogResponse();
//                BeanUtils.copyProperties(equipment,res);
//                res.setImei(equipment.getIMEI());
//                res.setEquipmentName(equipment.getName());
//                DictionaryItemRespDTO dict = holder.getDictionaryByKey(
//                        EquipmentType.DICT_CODE).stream().filter(a->a.getValue().equals(
//                        res.getEquipmentType())).collect(Collectors.toList()).get(0);
//                res.setEquipmentTypeName(dict.getName());
//                //设备状态  0:离线 1:正常 2:低报 3:高报 4:故障 5:屏蔽
//                String status = new String();
//                switch (request.getEquipmentStatus()) {
//                    case 0: status="离线";break;
//                    case 1: status="正常";break;
//                    case 2: status="低报";break;
//                    case 3: status="高报";break;
//                    case 4: status="故障";break;
//                    case 5: status="屏蔽";break;
//                }
//                res.setEquipmentStatusName( status );
//                if (map == null) {
//                    if (EquipmentStatus.offline == request.getEquipmentStatus()) {
//                        resultList.add(res);
//                    }
//                    continue;
//                }
//                LatestDetector latestDetector = null;
//                JSONObject json;
//                if (equipment.getEquipmentType().equals(EquipmentType.POINT_TYPE_GAS_DETECTOR.getCode())) {
//                    //探测器匹配时需截取后缀
//                    json = map.get(equipment.getIMEI().substring(0,equipment.getIMEI().length()-4));
//                } else {
//                    json = map.get(equipment.getIMEI());
//                }
//                if (json != null) {
//                    latestDetector = this.getLatestDetector(json);
//                }
//                if (latestDetector == null || latestDetector.getDetectorMeasures() == null ||
//                        latestDetector.getDetectorMeasures().isEmpty()) {
//                    //离线
//                    if (EquipmentStatus.offline == request.getEquipmentStatus()) {
//                        resultList.add(res);
//                    }
//                    continue;
//                }
//                //控制器
//                if (equipment.getEquipmentType().equals(EquipmentType.GAS_ALARM_CONTROLLER.getCode())) {
//                    LatestLog latestLog = this.get(res.getEquipmentType(),equipmentList.get(0).getPath(),res.getImei(),latestDetector);
//                    if (request.getEquipmentStatus().equals(latestLog.getEquipmentStatus())) {
//                        resultList.add(res);
//                    }
//                } else {
//                    DetectorMeasure detectorMeasure = null;
//                    for (DetectorMeasure measure : latestDetector.getDetectorMeasures()) {
//                        if (equipment.getEquipmentType().equals(EquipmentType.POINT_TYPE_GAS_DETECTOR.getCode())) {
//                            if (measure.getSubId().equals(equipment.getIMEI().substring(equipment.getIMEI().length()-3))) {
//                                detectorMeasure = measure;
//                            }
//                        } else{
//                            detectorMeasure = measure;
//                        }
//                    }
//                    if (detectorMeasure != null) {
//                        if (EquipmentStatus.lowAlert == detectorMeasure.getStatus() ||
//                                EquipmentStatus.highAlert == detectorMeasure.getStatus()) {
//                            if (EquipmentStatus.lowAlert == request.getEquipmentStatus() || EquipmentStatus.highAlert == request.getEquipmentStatus()) {
//                                resultList.add(res);
//                            }
//                        } else if (detectorMeasure.getStatus().equals(EquipmentStatus.broken) ||
//                                detectorMeasure.getStatus() == EquipmentStatus.sheild) {
//                            if (EquipmentStatus.broken == request.getEquipmentStatus()) {
//                                resultList.add(res);
//                            }
//                        } else if (detectorMeasure.getStatus().equals(EquipmentStatus.offline)) {
//                            if (EquipmentStatus.offline == request.getEquipmentStatus()) {
//                                resultList.add(res);
//                            }
//                        } else {
//                            if (EquipmentStatus.normal == request.getEquipmentStatus()) {
//                                resultList.add(res);
//                            }
//                        }
//                    } else {
//                        if (EquipmentStatus.offline == request.getEquipmentStatus()) {
//                            resultList.add(res);
//                        }
//                    }
//                }
//            }
//            int fromIndex = (request.getPage()-1)*request.getPageSize();
//            int toIndex = fromIndex+request.getPageSize();
//            if (toIndex > resultList.size()) {
//                toIndex = resultList.size();
//            }
//            total = resultList.size();
//            resultList = resultList.subList(fromIndex,toIndex);
//            //客户信息
//            List<Integer> consumerIds = resultList.stream().map(LatestLogResponse::getConsumerId).collect(Collectors.toList());
//            if (consumerIds != null && !consumerIds.isEmpty()) {
//                LambdaQueryWrapper<Consumer> consumerQueryWrapper = new LambdaQueryWrapper<>();
//                consumerQueryWrapper.eq(Consumer::getSpId,spId).in(Consumer::getId,consumerIds);
//                List<Consumer> consumerList = consumerService.list(consumerQueryWrapper);
//                for (LatestLogResponse latestLogResponse : resultList) {
//                    for (Consumer consumer : consumerList) {
//                        if (latestLogResponse.getConsumerId().equals(consumer.getId())) {
//                            latestLogResponse.setSubsCode(consumer.getSubsCode());
//                            latestLogResponse.setIndustryType(consumer.getIndustryType());
//                            latestLogResponse.setCustName(consumer.getCustName());
//                            latestLogResponse.setCustAddress(consumer.getCustAddress());
//                            latestLogResponse.setCustPhone(consumer.getCustPhone());
//                            //行业类型
//                            if (!StringUtils.isEmpty(latestLogResponse.getIndustryType())) {
//                                DictionaryItemRespDTO communicationModeDict = holder.getDictionaryByKey(
//                                        Constants.INDUSTRY_TYPE_CODE,spId).stream().filter(a->a.getValue().equals(
//                                        latestLogResponse.getIndustryType())).collect(Collectors.toList()).get(0);
//                                latestLogResponse.setIndustryTypeName(communicationModeDict.getName());
//                            }
//                        }
//                    }
//                }
//            }
//
//            for (LatestLogResponse res : resultList) {
//                LatestDetector latestDetector = null;
//                JSONObject json;
//                if (res.getEquipmentType().equals(EquipmentType.POINT_TYPE_GAS_DETECTOR.getCode())) {
//                    //探测器匹配时需截取后缀
//                    json = map.get(res.getImei().substring(0,res.getImei().length()-4));
//                } else {
//                    json = map.get(res.getImei());
//                }
//                if (json != null) {
//                    latestDetector = this.getLatestDetector(json);
//                }
//                LatestLog latestLog = this.get(res.getEquipmentType(),equipmentList.get(0).getPath(),res.getImei(),latestDetector);
//                if (latestLog != null) {
//                    BeanUtils.copyProperties(latestLog,res);
//                }
//            }
//        }
//
//        PageUtil pageInfo = new PageUtil<>(request.getPage(), request.getPageSize(), total, resultList);
//        return pageInfo;
//    }

//    @Override
//    public LatestLog get(String equipmentType, String path, String imei,LatestDetector latestDetector) {
//        String main = org.apache.commons.lang.StringUtils.substringBefore(imei, "-"); //截取 xxxx-1-11 的前缀
//        String sub = org.apache.commons.lang.StringUtils.substringAfter(imei, "-");   // 截取后缀
//        LatestLog log = new LatestLog();
//        log.setIMEI(imei);
//        if (EquipmentType.POINT_TYPE_GAS_DETECTOR.getCode().equals(equipmentType)) {
//            //探测器匹配时需截取后缀
//            if (latestDetector == null) {
//                JSONObject json =  (JSONObject) redisCacheExt.getHashObj(
//                        "department_" + path, main);
//                if (json == null) {
//                    log.setEquipmentStatus(EquipmentStatus.offline);
//                    return log;
//                }
//                latestDetector = getLatestDetector(json);
//            }
//            List<DetectorMeasure> list = latestDetector.getDetectorMeasures();
//            for (DetectorMeasure detectorMeasure : list) {
//                if (detectorMeasure.getSubId().equals(sub)) {
//                    //气体浓度
//                    log.setXlel(detectorMeasure.getValue()+detectorMeasure.getUnit());
//                    cn.hutool.json.JSONObject statusInfo = EquipmentStatus.getMsg(imei,equipmentType,latestDetector);
//                    if (statusInfo != null) {
//                        //设备状态 0:离线 1:正常 2:低报 3:高报 4:故障
//                        log.setEquipmentStatus(Integer.valueOf(statusInfo.get("status").toString()));
//                        //设备状态浮层
//                        log.setEquipmentStatusInfo(statusInfo.get("msg").toString());
//                        //离线时浓度为空
//                        if (EquipmentStatus.offline == log.getEquipmentStatus()) {
//                            log.setXlel("");
//                        }
//                    }
//                    //最近一次上报时间
//                    log.setLatestTime(DateUtil.parse(latestDetector.getTime(),"yyyy-MM-dd'T'HH:mm:ss"));
//                    //信号情况
//                    log.setSignal(SignalEnum.parse(latestDetector.getDtuMeasure().getSi()).getLevel());
//                    log.setSignalStr(SignalEnum.parse(latestDetector.getDtuMeasure().getSi()).getName());
//                    //电池电压
//                    log.setBtV(latestDetector.getDtuMeasure().getBtV());
//                    return log;
//                } else {
//                    //匹配不到该点位的redis数据，设置为离线
//                    log.setEquipmentStatus(EquipmentStatus.offline);
//                }
//            }
//        } else if (EquipmentType.GAS_ALARM_CONTROLLER.getCode().equals(equipmentType)){
//            if (latestDetector == null) {
//                JSONObject json =  (JSONObject) redisCacheExt.getHashObj(
//                        "department_" + path, imei);
//                if (json == null) {
//                    log.setEquipmentStatus(EquipmentStatus.offline);
//                    return log;
//                }
//                latestDetector = getLatestDetector(json);
//            }
//            cn.hutool.json.JSONObject statusInfo = EquipmentStatus.getMsg(imei,equipmentType,latestDetector);
//            if (statusInfo != null) {
//                //设备状态 0:离线 1:正常 2:低报 3:高报 4:故障
//                log.setEquipmentStatus(Integer.valueOf(statusInfo.get("status").toString()));
//                //设备状态浮层
//                log.setEquipmentStatusInfo(statusInfo.get("msg").toString());
//            }
//            //最近一次上报时间
//            log.setLatestTime(DateUtil.parse(latestDetector.getTime(),"yyyy-MM-dd'T'HH:mm:ss"));
//            //信号情况
//            log.setSignal(SignalEnum.parse(latestDetector.getDtuMeasure().getSi()).getLevel());
//            log.setSignalStr(SignalEnum.parse(latestDetector.getDtuMeasure().getSi()).getName());
//            //电池电压
//            log.setBtV(latestDetector.getDtuMeasure().getBtV());
//            return log;
//        } else {
//            if (latestDetector == null) {
//                JSONObject json =  (JSONObject) redisCacheExt.getHashObj(
//                        "department_"+path,imei);
//                if (json == null) {
//                    log.setEquipmentStatus(EquipmentStatus.offline);
//                    return log;
//                }
//                latestDetector = getLatestDetector(json);
//            }
//            List<DetectorMeasure> list = latestDetector.getDetectorMeasures();
//            for (DetectorMeasure detectorMeasure : list) {
//                //气体浓度
//                log.setXlel(detectorMeasure.getValue()+detectorMeasure.getUnit());
//                cn.hutool.json.JSONObject statusInfo = EquipmentStatus.getMsg(imei,equipmentType,latestDetector);
//                if (statusInfo != null) {
//                    //设备状态 0:离线 1:正常 2:低报 3:高报 4:故障
//                    log.setEquipmentStatus(Integer.valueOf(statusInfo.get("status").toString()));
//                    //设备状态浮层
//                    log.setEquipmentStatusInfo(statusInfo.get("msg").toString());
//                    //离线时浓度为空
//                    if (EquipmentStatus.offline == log.getEquipmentStatus()) {
//                        log.setXlel("");
//                    }
//                }
//            }
//            //最近一次上报时间
//            log.setLatestTime(DateUtil.parse(latestDetector.getTime(),"yyyy-MM-dd'T'HH:mm:ss"));
//            //信号情况
//            log.setSignal(SignalEnum.parse(latestDetector.getDtuMeasure().getSi()).getLevel());
//            log.setSignalStr(SignalEnum.parse(latestDetector.getDtuMeasure().getSi()).getName());
//            //电池电压
//            log.setBtV(latestDetector.getDtuMeasure().getBtV());
//            return log;
//        }
//        return log;
//    }

//    @Override
//    public LatestDetector getLatestDetector(JSONObject json) {
//        if (json == null) {
//            return null;
//        }
//        LatestDetector latestDetector = new LatestDetector();
//        latestDetector = new LatestDetector();
//        latestDetector.setTime(json.getString("time"));
//        latestDetector.setDtuId(json.getString("dtuId"));
//        latestDetector.setType(Integer.valueOf(json.getString("type")));
//        latestDetector.setCommand(Integer.valueOf(json.getString("command")));
//        latestDetector.setDtuMeasure( JSONUtil.toBean(json.getString("dtuMeasure"), DtuMeasure.class));
//        latestDetector.setDetectorMeasures(JSONUtil.toList(json.getString("detectorMeasures"),DetectorMeasure.class));
//        return latestDetector;
//    }



    public Object dealContacts(List<Contacts> contacts) {
        log.info("dealContacts-param:{}",JSONObject.toJSONString(contacts));
        String[] result = new String[50];
        if (CollectionUtils.isEmpty(contacts)) return result;
        Map<Integer, List<Contacts>> collect = contacts.stream().collect(Collectors.groupingBy(Contacts::getLevel));
        int j = 0;
        for (int i = -1; i < 20; i = i + 2) {
            List<Contacts> con = collect.get(j + 1);
            if (CollectionUtils.isEmpty(con)) {
                result[i + 1] = "";
                result[i + 2] = "";
            } else {
                Contacts contacts1 = con.get(0);
                result[i + 1] = contacts1.getName();
                result[i + 2] = contacts1.getTelephone();
            }
            j++;
        }
        j = 0;
        for (int i = 20; i < 30; i++) {
            List<Contacts> con = collect.get(j + 1);
            if (CollectionUtils.isEmpty(con)) {
                result[i] ="";
            }else {
                Contacts contacts1 = con.get(0);
                result[i] = contacts1.getLevel()+"";
            }
            j++;
        }
        return (Object) result;
    }

}
